package leetcode.to1000;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.PriorityQueue;

public class T0502 {
    class Solution {
        public int findMaximizedCapital(int k, int w, int[] profits, int[] capital) {
            int n = profits.length;
            List<int[]> list = new ArrayList<>();
            for (int i = 0; i < n; i++) {
                list.add(new int[]{capital[i], profits[i]});
            }
            Collections.sort(list, (a, b)->a[0]-b[0]);
            PriorityQueue<Integer> queue = new PriorityQueue<>((a, b)->b-a);
            int i = 0;
            while (k-- > 0) {
                while (i < n && list.get(i)[0] <= w) queue.add(list.get(i++)[1]);
                if (queue.isEmpty()) break;
                w += queue.poll();
            }
            return w;
        }
    }
}
